//同时接收普通数据和带外数据
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
/*
ssize_t recv(int sockfd,void *buf,size_t len,int flags);
recv读取sockfd上的数据，buf和len参数分别指定读取缓冲区的位置和大小。
*/
#define BUF_SIZE 1024
int main(int argc,char*argv[])
{
    if(argc <=2)
    {
        printf("usage: %s ip_address port_number \n",
        basename(argv[0]));
        return 1;
    }

    const char* ip = argv[1];
    int port = atoi(argv[2]);

   

    /*创建一个IPv4 socket地址*/
    struct sockaddr_in address;
    bzero(&address,sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(AF_INET,ip,&address.sin_addr);
    address.sin_port= htons(port);

    int listenfd = socket(PF_INET,SOCK_STREAM,0);
    assert(listenfd>=0);

    int ret = bind(listenfd,(struct sockaddr*)&address,sizeof(address));
    assert(ret != -1);
    ret = listen(listenfd,5);
    assert(ret !=-1);

    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);
    int connfd = accept(listenfd,(struct sockaddr*)&client,&client_addrlength);
    if(connfd <0)
    {
        printf("errno is: %d\n",errno);
        close(listenfd);
    }

    char buf[1024];
    fd_set read_fds;        //可读事件对应的文件描述符集合
    fd_set exception_fds;   //异常事件对应的文件描述符集合
    FD_ZERO(&read_fds);
    FD_ZERO(&exception_fds);
    while(1)
    {
        memset(buf,'\0',sizeof(buf));
        /*每次调用select前都要重新在read_fds和exception_fds中设置文件描述符
        connfd,因为事件发生后，文件描述符集合将衩内核修改*/
        FD_SET(connfd,&read_fds);//将所有要监听的夽接字文件描述符集合传递进去
        FD_SET(connfd,&exception_fds);
        ret = select(connfd +1,&read_fds,NULL,&exception_fds,NULL);
        if(ret <= 0)
        {
            printf("selection failure\n");
            break;
        }
        /*对于可读事件，采用普通的recv函数读取数据*/
        if(FD_ISSET(connfd,&read_fds))
        {
            ret = recv(connfd,buf,sizeof(buf)-1,0);
            if(ret<=0)
            {
                break;
            }
            printf("Get %d bytes of normal data: %s\n",ret,buf);
        }/*对于异常事件，采用带MSG_OOB标志的recv函数读取带外数据*/
        else if(FD_ISSET(connfd,&exception_fds))
        {
            ret = recv(connfd,buf,sizeof(buf) -1,MSG_OOB);
            if(ret <=0)
            {
                break;
            }
            printf("Get %d bytes oob data: %s\n",ret,buf);
        }
    }
    close(connfd);
    close(listenfd);
    return 0;
}

